package com.myutils;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;

import org.apache.axis.Constants;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.log4j.Logger;

/**
 * @author Lan
 * @date 2012-7-1
 */
public class AxisWSUtil {

	protected static Logger logger = Logger.getLogger(AxisWSUtil.class);
	
	public static Object execute(String url, String nameSpace, String methodName,
			Map<String, String> parameters) {
		Object resp = "";
		Service service = new Service();
		try {
			Call call = (Call) service.createCall();
			call.setTargetEndpointAddress(new URL(url));

			call.setOperationName(new QName(nameSpace, methodName));

			List<String> paramValues = new ArrayList<String>();
			for (Map.Entry<String, String> entry : parameters.entrySet()) {
				String paramName = entry.getKey();
				String paramValue = entry.getValue();

				call.addParameter(new QName(nameSpace, paramName),
						XMLType.XSD_STRING, ParameterMode.IN);
				paramValues.add(paramValue);
			}

			call.setUseSOAPAction(true);
			call.setReturnType(Constants.XSD_STRING);// 设置返回类型
			call.setSOAPActionURI(nameSpace + methodName);

			resp = call.invoke(paramValues.toArray());
		} catch (ServiceException e) {
			logger.error("创建Call对象失败", e);
		} catch (MalformedURLException e) {
			logger.error("创建URL对象失败", e);
		} catch (RemoteException e) {
			logger.error("调用远程webservice接口失败", e);
		}
		return resp;
	}

	public static Object execute(String endPoint, String nameSpace, String methodName,
			String paramName, String paramValue) {
		Object resp = "";
		Service service = new Service();
		try {
			Call call = (Call) service.createCall();
			call.setTargetEndpointAddress(new URL(endPoint));

			call.setOperationName(new QName(nameSpace, methodName));

			call.addParameter(new QName(nameSpace, paramName),
					XMLType.XSD_STRING, ParameterMode.IN);

			call.setReturnType(XMLType.SOAP_ELEMENT);// 设置返回类型
			call.setUseSOAPAction(true);
			call.setSOAPActionURI(nameSpace + methodName);
			resp = call.invoke(new Object[] { paramValue });
		} catch (ServiceException e) {
			logger.error("创建Call对象失败", e);
		} catch (MalformedURLException e) {
			logger.error("创建URL对象失败", e);
		} catch (RemoteException e) {
			logger.error("调用远程webservice接口失败", e);
		}
		return resp;
	}
}
